import { defineStore } from 'pinia'
import { stores } from '../index'
import type { AppRoute, AppMenu } from '@/router/types'
import { transformRouteToMenu } from '@/router/helper/menuHelper'
import { asyncRoutes } from '@/router/routes'
import { useAppStoreWithOut } from './app'
import { appSetting } from '@/settings/appBaseSetting'
import { PermissionModeEnum } from '@/enums/appEnum'
import { getMeRouter } from '@/api/system/menu'
import Layout from '@/layout'
interface PermissionState {
  menuList: AppMenu[]
  meRouterList: any[]
  permCodeList: string[]
  routerLoad: boolean
}
const viewsModules: any = import.meta.glob('../../views/**/*.tsx')
const dynamicViewsModules: Record<string, Function> = Object.assign({}, { ...viewsModules })

export const usePermissionStore = defineStore('app-permission', {
  state: (): PermissionState => ({
    menuList: [],
    meRouterList: [],
    permCodeList: [],
    routerLoad: false
  }),
  getters: {
    getMenuList(): AppMenu[] {
      return this.menuList
    },
    getMeRouterList(): any[] {
      return this.meRouterList
    },
    getPermCodeList(): string[] {
      return this.permCodeList
    },
    getRouterLoad(): boolean {
      return this.routerLoad
    }
  },
  actions: {
    setMenuList(list: AppMenu[]) {
      this.menuList = list
    },
    setMeRouterList(routerList: any[]) {
      this.meRouterList = routerList
    },
    setRouterLoad(isLoad: boolean) {
      this.routerLoad = isLoad
    },
    setPermCodeList(list: string[]) {
      this.permCodeList = list
    },
    async buildRoutesAction(): Promise<AppRoute[]> {
      // 加载路由
      const appStore = useAppStoreWithOut()
      let routes: AppRoute[] = []
      this.setRouterLoad(true)
      const { permissionMode = appSetting.permissionMode } = appStore.getAppConfig
      if (permissionMode === PermissionModeEnum.MAPPING) {
        routes = asyncRoutes
      } else {
        routes = transformRoutes(await getMeRouter())
      }
      this.setMeRouterList(routes)
      const menuList = transformRouteToMenu(routes)
      menuList.sort((a, b) => {
        return (a?.orderNo || menuList.length) - (b?.orderNo || menuList.length)
      })
      this.setMenuList(menuList)
      return routes
    },
    resetState(): void {
      this.menuList = []
      this.meRouterList = []
      this.permCodeList = []
      this.routerLoad = false
    }
  }
})

/**
 * 转换路由数据为组件
 */
const transformRoutes = (routes: any[]) => {
  const asyncRoutes: any[] = []
  routes.forEach(route => {
    const tmpRoute = { ...route } as any
    if (!tmpRoute.path) {
      tmpRoute.path = ''
    }
    if (tmpRoute.component?.toString() == 'Layout') {
      // 顶级目录，替换为 Layout 组件
      tmpRoute.component = Layout
    } else {
      // 其他菜单，根据组件路径动态加载组件
      if (tmpRoute.component) {
        tmpRoute.component = dynamicImport(dynamicViewsModules, tmpRoute.component as string)
      } else {
        tmpRoute.component = import(`../../views/exception/index`)
      }
    }

    if (tmpRoute.children) {
      tmpRoute.children = transformRoutes(route.children)
    }
    asyncRoutes.push(tmpRoute)
  })

  return asyncRoutes
}

/**
 * 后端路由 component 转换函数
 * @param dynamicViewsModules 获取目录下的 .vue、.tsx 全部文件
 * @param component 当前要处理项 component
 * @returns 返回处理成函数后的 component
 */
export const dynamicImport = (dynamicViewsModules: Record<string, Function>, component: string) => {
  const keys = Object.keys(dynamicViewsModules)
  const matchKeys = keys.filter(key => {
    const k = key.replace(/..\/..\/views|../, '')
    return k.startsWith(`${component}`) || k.startsWith(`/${component}`)
  })
  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0]
    return dynamicViewsModules[matchKey]
  }
  if (matchKeys?.length > 1) {
    return false
  }
}

// Need to be used outside the setup
export function usePermissionStoreWithOut() {
  return usePermissionStore(stores)
}
